package com.ruoyi.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.text.UnicodeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.system.RSAUtils;
import com.ruoyi.system.domain.bo.HiasActiveCheckBo;
import com.ruoyi.system.domain.bo.HiasActiveCheckSafeBo;
import com.ruoyi.system.domain.bo.HiasActiveGenBo;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import com.ruoyi.system.domain.bo.HiasActiveBo;
import com.ruoyi.system.domain.vo.HiasActiveVo;
import com.ruoyi.system.domain.HiasActive;
import com.ruoyi.system.mapper.HiasActiveMapper;
import com.ruoyi.system.service.IHiasActiveService;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.util.*;

/**
 * 激活码Service业务层处理
 *
 * @author ruoyi
 * @date 2024-03-09
 */
@RequiredArgsConstructor
@Service
public class HiasActiveServiceImpl implements IHiasActiveService {

    private final HiasActiveMapper baseMapper;

    private static final RedissonClient CLIENT = SpringUtils.getBean(RedissonClient.class);

    /**
     * 查询激活码
     */
    @Override
    public HiasActiveVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询激活码列表
     */
    @Override
    public TableDataInfo<HiasActiveVo> queryPageList(HiasActiveBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<HiasActive> lqw = buildQueryWrapper(bo);
        Page<HiasActiveVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询激活码列表
     */
    @Override
    public List<HiasActiveVo> queryList(HiasActiveBo bo) {
        LambdaQueryWrapper<HiasActive> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<HiasActive> buildQueryWrapper(HiasActiveBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<HiasActive> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getActiveCode() != null, HiasActive::getActiveCode, bo.getActiveCode());
        lqw.eq(bo.getType() != null, HiasActive::getType, bo.getType());
        lqw.eq(bo.getActiveDuration() != null, HiasActive::getActiveDuration, bo.getActiveDuration());
        lqw.eq(bo.getActiveState() != null, HiasActive::getActiveState, bo.getActiveState());
        lqw.eq(StringUtils.isNotBlank(bo.getActiveDevice()), HiasActive::getActiveDevice, bo.getActiveDevice());
        lqw.eq(bo.getActiveSerial() != null, HiasActive::getActiveSerial, bo.getActiveSerial());
        lqw.eq(bo.getActiveTime() != null, HiasActive::getActiveTime, bo.getActiveTime());
        return lqw;
    }

    /**
     * 新增激活码
     */
    @Override
    public Boolean insertByBo(HiasActiveBo bo) {
        HiasActive add = BeanUtil.toBean(bo, HiasActive.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改激活码
     */
    @Override
    public Boolean updateByBo(HiasActiveBo bo) {
        HiasActive update = BeanUtil.toBean(bo, HiasActive.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(HiasActive entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除激活码
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public R generateActiveCode(HiasActiveGenBo genBo) {
        String activeCode = UUID.randomUUID().toString();
        HiasActive active = new HiasActive();
        active.setActiveCode(activeCode);
        active.setActiveDuration(genBo.getActiveDuration());
        active.setActiveState(0L);
        active.setType(genBo.getType());
        baseMapper.insert(active);
        return R.ok("激活码生成成功");
    }

    @Override
    public R activeCheck(HiasActiveCheckBo activeCheckBo) {
        //检查激活码的状态
        QueryWrapper<HiasActive> wrapper = new QueryWrapper<>();
        wrapper.eq("active_code", activeCheckBo.getActiveCode());
        List<HiasActive> actives = baseMapper.selectList(wrapper);
        HiasActive active = actives.get(0);
        if(active.getActiveState()==0) {
            //未使用过，将设备ID和授权码绑定
            active.setActiveDevice(activeCheckBo.getActiveDevice());
            active.setActiveTime(new Date());
            active.setActiveSerial(activeCheckBo.getActiveSerial());
            active.setActiveState(1L);
            baseMapper.updateById(active);
            return R.ok("激活成功");
        }else if(active.getActiveState()==1) {
            //已经和设备绑定，检查设备编码是否一致
            if(active.getActiveDevice().equals(activeCheckBo.getActiveDevice())) {
                //检查串号，防止有人重发请求
                if(activeCheckBo.getActiveSerial()-active.getActiveSerial()==1) {
                    //检查过期时间
                    active.setActiveSerial(activeCheckBo.getActiveSerial());
                    baseMapper.updateById(active);
                    return R.ok("激活成功");
                }else {
                    return R.fail("串号检查失败");
                }
            }else {
                return R.fail("此激活码重复激活，请使用新的激活码");
            }
        }
        return R.fail("授权码错误");
    }

    @Override
    public R activeCheckSafe(HiasActiveCheckSafeBo safeBo) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        Gson gson = new Gson();
        HiasActiveCheckBo activeCheckBo = gson.fromJson(safeBo.getSafeStr(), HiasActiveCheckBo.class);
        return R.ok(activeCheckBo);
    }
}
